﻿// <copyright file="DetailPage.xaml.cs" company="Microsoft Corporation">
// Copyright (c) 2009 Microsoft Corporation All Rights Reserved
// </copyright>
// <author>Michael S. Scherotter</author>
// <email>mischero@microsoft.com</email>
// <date>2010-09-13</date>
// <summary>DetailPage code behind</summary>

namespace MostPopular
{
    using System;
    using System.Device.Location;
    using System.Globalization;
    using System.Linq;
    using System.Windows;
    using System.Windows.Controls;
    using Microsoft.Advertising.Mobile.UI;
    using Microsoft.Phone.Controls;
    using Microsoft.Phone.Shell;
    using Microsoft.Phone.Tasks;
    using MostPopular.ViewModels;
    using NYTimes.Data;

    /// <summary>
    /// Article detail page
    /// </summary>
    public partial class DetailPage : PhoneApplicationPage, IDisposable
    {
        /// <summary>
        /// The Geographic coordinate watcher
        /// </summary>
        private GeoCoordinateWatcher watcher;

        /// <summary>
        /// The comments
        /// </summary>
        private MostPopularItemComments comments;

        /// <summary>
        /// Initializes a new instance of the DetailPage class.
        /// </summary>
        public DetailPage()
        {
            AdControl.TestMode = false;

            this.watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default);

            this.watcher.Start();

            this.InitializeComponent();

            this.DataContext = App.ViewModel.SelectedItem;

            this.Loaded += new RoutedEventHandler(this.DetailPage_Loaded);

            this.watcher.StatusChanged += new EventHandler<GeoPositionStatusChangedEventArgs>(this.OnWatcherStatusChanged);
        }

        /// <summary>
        /// Dispose of the resources
        /// </summary>
        public void Dispose()
        {
            this.Dispose(true);
        }

        /// <summary>
        /// Set the location
        /// </summary>
        /// <param name="sender">the geo coordinate watcher</param>
        /// <param name="e">the geo position status changed event arguments</param>
        private void OnWatcherStatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
        {
            if (e.Status == GeoPositionStatus.Ready)
            {
                this.AdControl.Location = new Location(this.watcher.Position.Location.Latitude, this.watcher.Position.Location.Longitude);
            }
        }

        /// <summary>
        /// Set the keywords
        /// </summary>
        /// <param name="sender">the detail page></param>
        /// <param name="e">the routed event arguments</param>
        private void DetailPage_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            this.AdControl.AdSelectionKeywords = this.GetKeywords();

            var context = this.DataContext as NYTimes.Data.MostPopularItem;

            this.comments = new MostPopularItemComments
            {
                Comments = new NYTimes.CommunityCommentsByUrl
                {
                    ApiKey = "813ad46f5104333600149585f06dd2e3:18:57351476",
                    Url = context.Url
                },
                Item = context,
            };

            this.comments.Comments.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(this.Comments_PropertyChanged);

            if (context.GeoFacets.Count == 0)
            {
                var mapButton = (from button in this.ApplicationBar.Buttons.Cast<ApplicationBarIconButton>()
                                  where button.Text == "Map"
                                  select button).FirstOrDefault();

                if (mapButton != null)
                {
                    mapButton.IsEnabled = false;
                }
            }
        }

        /// <summary>
        /// When the comments changed, enable/disable the comments buttons
        /// </summary>
        /// <param name="sender">the comments object</param>
        /// <param name="e">the property changed event arguments</param>
        private void Comments_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            var commentsButton = (from button in this.ApplicationBar.Buttons.Cast<ApplicationBarIconButton>()
                                  where button.Text == "Comments"
                                  select button).FirstOrDefault();

            if (commentsButton != null)
            {
                commentsButton.IsEnabled = this.comments.Comments.Results.Count > 0;
            }
        }

        /// <summary>
        /// Gets a | -delimited list of keywords with a maximum of 100 characters for the AdControl.AdSelectionKeywords
        /// </summary>
        /// <returns>a | delimited list of keywords with a maximum of 100 characters</returns>
        private string GetKeywords()
        {
            var context = this.DataContext as NYTimes.Data.MostPopularItem;

            var keywords = string.Join("|", context.DescriptionFacets.ToArray());

            if (keywords.Length >= 100)
            {
                var index = keywords.LastIndexOf('|');

                keywords = keywords.Substring(0, index);
            }

            return keywords;
        }

        /// <summary>
        /// Navigate to the article
        /// </summary>
        /// <param name="sender">the button</param>
        /// <param name="e">the event arguments</param>
        private void OnClickReadButton(object sender, System.EventArgs e)
        {
            var button = sender as Button;

            var context = this.DataContext as MostPopularItem;

            var task = new WebBrowserTask();

            task.URL = context.Url.ToString();

            task.Show();
        }

        #region IDisposable Members

        /// <summary>
        /// Dispose of the resources
        /// </summary>
        /// <param name="disposing">true if disposing</param>
        private void Dispose(bool disposing)
        {
            if (this.watcher != null)
            {
                this.watcher.Dispose();

                this.watcher = null;
            }
        }

        #endregion

        /// <summary>
        /// Navigate the map page
        /// </summary>
        /// <param name="sender">the application bar icon button</param>
        /// <param name="e">the event arguments</param>
        private void MapButton_Click(object sender, EventArgs e)
        {
            if (NavigationService.Navigate(new Uri("/MapPage.xaml", UriKind.Relative)))
            {
                var context = this.DataContext as MostPopularItem;

                FrameworkElement root = Application.Current.RootVisual as FrameworkElement;

                root.DataContext = context;
            }
        }

        /// <summary>
        /// Navigate to the comments page
        /// </summary>
        /// <param name="sender">the application bar icon button</param>
        /// <param name="e">the event arguments</param>
        private void CommentsButton_Click(object sender, EventArgs e)
        {
            if (NavigationService.Navigate(new Uri("/CommentsPage.xaml", UriKind.Relative)))
            {
                FrameworkElement root = Application.Current.RootVisual as FrameworkElement;

                root.DataContext = this.comments;
            }
        }

        /// <summary>
        /// Send an email message about the current article
        /// </summary>
        /// <param name="sender">the email button</param>
        /// <param name="e">the event arguments</param>
        private void EmailButton_Click(object sender, EventArgs e)
        {
            var task = new EmailComposeTask()
            {
                Body = string.Format(
                    CultureInfo.CurrentCulture, 
                    Properties.Resources.EmailBody,
                    this.comments.Item.Title,
                    this.comments.Item.Abstract,
                    this.comments.Item.Url,
                    this.comments.Item.Source),
                Subject = string.Format(
                    CultureInfo.CurrentCulture, 
                    Properties.Resources.EmailSubject, 
                    this.comments.Item.Source, 
                    this.comments.Item.Title)
            };

            task.Show();
        }
    }
}
